<template>
  <div style="height:100%">
    <el-row type="flex" class="personnel-main">
      <el-col class="left">
        <div class="search-box">
          <!-- <el-input
          size="small"
          v-model="searchInput"
          placeholder="搜索部门"
          prefix-icon="el-icon-search"
          class="mb10"
        /> -->
          <el-tree
            node-key="id"
            accordion
            :props="defaultProps"
            :load="loadNode"
            @node-click="nodeClick"
            :expand-on-click-node="false"
            lazy
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <div v-if="node.label == '新华源'">
                <img
                  :src="require('@/assets/img/dispatch/' + node.label + '.png')"
                  width="88"
                  height="18"
                />
              </div>
              <div v-else-if="node.label == '恒源'">
                <img
                  :src="require('@/assets/img/dispatch/' + node.label + '.png')"
                  width="62"
                />
              </div>
              <div v-else>
                <svg-icon :icon-class="'label' + node.level" />
                {{ node.label }}
              </div>
            </div>
          </el-tree>
        </div>
      </el-col>
      <el-col class="right">
        <el-row type="flex" justify="space-between" align="middle">
          <div style="font-size:13px;color:#9EA2BA;">
            <span style="font-size:16px;color:#39475D;margin-right:10px">{{
              selectSearch.bc
            }}</span>
            <svg-icon
              icon-class="person"
              class-name="custom-class"
              style="font-size:16px"
            />
            <span style="color:#606D86">{{ total }}</span>
            人
          </div>
          <div>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="showDialog('add')"
              >新增人员</el-button
            >
            <el-button size="small">批量导入/导出</el-button>
            <el-button size="small">变更工种</el-button>
            <el-button
              size="small"
              type="danger"
              class="danger-btn"
              @click="delPerson('', 'multiple')"
              >操作删除</el-button
            >
          </div>
        </el-row>
        <div class="common-table" ref="table" style="margin-top:15px">
          <el-table
            ref="personTable"
            v-loading="tableLoading"
            :data="tableData"
            style="width: 100%"
            :max-height="tableHeight"
            @row-click="rowClick"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="姓名" min-width="15%" align="center">
              <template slot-scope="{ row }">
                <el-row type="flex" justify="center" align="middle">
                  <img
                    v-if="row.head_img"
                    :src="row.head_img"
                    width="20"
                    height="20"
                    style="margin-right:8px"
                  />
                  {{ row.name }}
                </el-row>
              </template>
            </el-table-column>
            <el-table-column
              prop="sex"
              label="性别"
              min-width="10%"
              align="center"
            />
            <el-table-column
              prop="gh"
              label="工号"
              min-width="10%"
              align="center"
            />
            <el-table-column
              prop="org"
              label="组织"
              min-width="10%"
              align="center"
            />
            <el-table-column
              prop="cj"
              label="车间"
              min-width="10%"
              align="center"
            />
            <el-table-column
              prop="gongxu"
              label="工序"
              min-width="10%"
              align="center"
            />
            <el-table-column
              prop="workType"
              label="工种"
              min-width="10%"
              align="center"
            />
            <el-table-column label="班次" min-width="10%" align="center">
              <template slot-scope="{ row }">
                <el-tag v-if="row.bc == '甲班'" size="mini" class="table-tag"
                  >甲班</el-tag
                >
                <el-tag
                  v-else
                  size="mini"
                  class="table-tag"
                  color="#E9D1FF"
                  style="color:#7100D5"
                  >{{ row.bc }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="{ row }">
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  size="small"
                  style="padding:0"
                  @click.stop="showDialog('edit', row)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  class="danger"
                  style="padding:0"
                  size="small"
                  @click.stop="delPerson(row.gh)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="common-pagination">
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper"
            :page-size="search.size"
            :current-page.sync="search.current"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      width="760px"
      :visible="dialogVisible"
      @close="closeDialog"
      title="新增人员"
      center
      custom-class="person-dialog"
    >
      <el-form
        ref="addForm"
        :model="add"
        label-width="60px"
        hide-required-asterisk
        :rules="rules"
      >
        <el-row type="flex">
          <el-col :span="19">
            <h4>基本信息</h4>
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input
                    v-model="add.name"
                    size="small"
                    placeholder="请输入姓名"
                  ></el-input>
                </el-form-item>
                <el-form-item label="工号" prop="gh">
                  <el-input
                    v-model="add.gh"
                    size="small"
                    placeholder="请输入工号"
                  ></el-input>
                </el-form-item>
                <el-form-item label="组织" prop="org">
                  <el-select
                    v-model="add.org"
                    placeholder="请选择组织"
                    size="small"
                  >
                    <el-option
                      v-for="item in orgOption"
                      :key="item.id"
                      :label="item['key_value']"
                      :value="item['key_value']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-select
                    v-model="add.sex"
                    size="small"
                    placeholder="请选择性别"
                  >
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="集团" prop="group">
                  <el-select
                    v-model="add.group"
                    placeholder="请选择集团"
                    size="small"
                  >
                    <el-option
                      v-for="item in groupOption"
                      :key="item.id"
                      :label="item['key_value']"
                      :value="item['key_value']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <h4>工种工序信息</h4>
            <el-row>
              <el-col :span="12">
                <el-form-item label="车间" prop="cj">
                  <el-select
                    v-model="add.cj"
                    placeholder="请选择车间"
                    size="small"
                  >
                    <el-option
                      v-for="item in cjOption"
                      :key="item.id"
                      :label="item['key_value']"
                      :value="item['key_value']"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="工种" prop="workType">
                  <el-select
                    v-model="add.workType"
                    placeholder="请选择工种"
                    size="small"
                  >
                    <el-option
                      v-for="item in wtOption"
                      :key="item.id"
                      :label="item['key_value']"
                      :value="item['key_value']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工序" prop="gongxu">
                  <el-select
                    v-model="add.gongxu"
                    placeholder="请选择工序"
                    size="small"
                    @change="changeGX"
                  >
                    <el-option
                      v-for="item in gxOption"
                      :key="item.id"
                      :label="item['key_value']"
                      :value="{
                        value: item['key_value'],
                        name: item['key_name']
                      }"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="班次" prop="bc">
                  <el-select
                    v-model="add.bc"
                    placeholder="请选择班次"
                    size="small"
                  >
                    <el-option
                      v-for="item in bcOption"
                      :key="item.id"
                      :label="item['key_value']"
                      :value="item['key_value']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="4" :offset="1">
            <h4>用户头像</h4>
            <el-upload
              class="avatar-uploader"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="add.head_img" :src="add.head_img" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPerson,
  updatePerson,
  getPersonList,
  delPerson,
  getPersonnelGroup
} from '@/api/person.js';
import { getSysDict } from '@/api/common.js';
export default {
  props: ['selectSearch'],
  data() {
    return {
      action: localStorage.getItem('baseURL') + '/common/uploadImage',
      tableHeight: 200,
      search: {
        size: 10,
        current: 1
      },
      changeSearch: {
        cj: '',
        bc: '',
        gongxu: '',
        group: '',
        org: '',
        workType: ''
      },
      add: {
        bc: '',
        cj: '',
        gh: '',
        gongxu: '',
        group: '',
        head_img: '',
        name: '',
        org: '',
        sex: '',
        workType: ''
      },
      group: [],
      wtOption: [],
      dialogVisible: false,
      dialogType: 'add',
      // 树
      defaultProps: {
        children: 'data',
        label: 'key_value'
      },
      total: 10,
      tableData: [],
      tableLoading: false,
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        gh: [{ required: true, message: '请输入工号', trigger: 'blur' }]
      },
      imageUrl: ''
    };
  },
  computed: {
    gxOption() {
      return this.$store.getters.gxOption;
    },
    cjOption() {
      return this.$store.getters.cjOption;
    },
    orgOption() {
      return this.$store.getters.orgOption;
    },
    bcOption() {
      return this.$store.getters.bcOption;
    },
    groupOption() {
      return this.$store.getters.groupOption;
    }
  },
  mounted() {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至';
    this.$nextTick(() => {
      this.getHeight();
    });
    this.getTableData();
  },
  methods: {
    getHeight() {
      this.tableHeight = this.$refs.table.offsetHeight;
    },
    getPerson() {},
    // 树节点切换
    nodeClick(data, node) {
      this.changeSearch = {
        cj: '',
        group: '',
        org: '',
        gongxu: '',
        workType: '',
        bc: ''
      };
      this.changeSearch[node.data.key_query] = node.data.key_value;
      if (node.level !== 1) {
        this.mapParent(node.parent);
      }
      this.$emit('change', this.changeSearch);
      this.search.current = 1;
      this.$nextTick(() => {
        this.getTableData();
      });
    },
    mapParent(node) {
      if (node && node.level > 0) {
        let { data } = node;
        this.changeSearch[data.key_query] = data.key_value;
        this.mapParent(node.parent);
      }
    },
    rowClick(row) {
      this.$router.push({ path: '/DispatchPersonnel/Detail' });
    },
    async getTableData(resetPage) {
      this.tableLoading = true;
      if (resetPage) {
        this.search.current = 1;
      }
      let query = Object.assign({}, this.selectSearch, this.search);
      const res = await getPersonList(query);
      if (res.code == 1) {
        let { data } = res;
        this.tableData = data.records;
        this.total = data.total;
        this.tableLoading = false;
      }
    },
    delPerson(id, type) {
      let ids = [];
      if (type == 'multiple') {
        let selection = this.$refs.personTable.selection;
        if (selection.length > 0) {
          selection.map(item => {
            ids.push(item.gh);
          });
        } else {
          this.$message({
            message: '请选择需要删除的人员',
            iconClass: 'el-icon-warning',
            customClass: 'common-message'
          });
          return;
        }
      } else {
        ids = [id];
      }
      this.$confirm('是否确认删除该人员?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await delPerson(ids);
        if (res.code == 1) {
          this.$message({
            message: '删除成功',
            iconClass: 'el-icon-success',
            customClass: 'common-message'
          });
          this.getTableData(true);
        }
      });
    },
    handleSizeChange(val) {
      this.search.current = 1;
      this.search.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.current = val;
      this.getTableData();
    },
    async loadNode(node, resolve) {
      let form = node.level === 0 ? 'groupTreeTop' : node.data.key_name;
      const res = await getPersonnelGroup({ keyName: form });
      if (res.code === 1) {
        if (node.level == 5 && res.data.length == 0) {
          if (node.parent.data.key_value == '细纱') {
            return resolve([
              { key_name: '甲班', key_value: '甲班', key_query: 'bc' },
              { key_name: '乙班', key_value: '乙班', key_query: 'bc' }
            ]);
          } else {
            return resolve([
              { key_name: '甲班', key_value: '甲班', key_query: 'bc' },
              { key_name: '乙班', key_value: '乙班', key_query: 'bc' },
              { key_name: '丙班', key_value: '丙班', key_query: 'bc' }
            ]);
          }
        } else {
          return resolve(res.data);
        }
      }
    },
    // 头像
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.add.head_img = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /***************** 弹窗 ***************/
    async changeGX(val) {
      this.add.workType = '';
      this.wtOption = [];
      let workType = 'workType_' + val.name;
      const res = await getSysDict(workType);
      if (res.code == 1) {
        this.wtOption = res.data.dataList;
      }
    },
    // 添加或修改人员
    confirm() {
      this.$refs['addForm'].validate(async valid => {
        if (valid) {
          if (this.dialogType == 'add') {
            let form = Object.assign({}, this.add);
            form.gongxu = this.add.gongxu.value;
            const d = await addPerson(form);
            if (d.status === 'success') {
              this.$message.success('添加成功');
              this.dialogVisible = false;
            }
          } else {
            let form = Object.assign({}, this.add);
            form.gongxu = this.add.gongxu.value
              ? this.add.gongxu.value
              : this.add.gongxu;
            const d = await updatePerson(form);
            if (d.status === 'success') {
              this.$message.success('添加成功');
              this.dialogVisible = false;
            }
          }
        } else {
          this.$message.warning('请输入必填项');
          return false;
        }
      });
    },
    showDialog(type, row) {
      if (type == 'edit') {
        this.add = Object.assign({}, row);
      }
      this.dialogType = type;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.$refs['addForm'].resetFields();
      this.$refs['addForm'].clearValidate();
      this.dialogVisible = false;
      this.add.head_img = '';
      this.getTableData();
    }
  }
};
</script>

<style lang="scss" scoped>
.common-table {
  height: calc(100% - 95px);
}
.search-box {
  height: 100%;
  overflow-y: auto;
  margin: 0;
  box-sizing: border-box;
  .el-tree {
    ::v-deep.el-tree-node__content {
      height: 42px;
      font-size: 15px;
      color: #48556a;
      border-bottom: 1px solid #f0f2f6;
      .svg-icon {
        font-size: 18px;
        margin-right: 8px;
      }
    }
    .el-tree-node.is-current > .el-tree-node__content > .custom-tree-node {
      color: #2c67f6;
    }
  }
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar {
  width: 90px;
  height: 90px;
  display: block;
}
.person-dialog {
  h4 {
    font-size: 15px;
  }
}
</style>
